<template>
  <section v-loading="pageLoading" style="height:100%;">
    <el-container style="height:100%;">
      <el-container>
        <el-header class="header" height="auto" style="padding:5px 10px 5px 10px;text-align:right;">
          <span style="float:left;font-size:14px;line-height: 28px;">{{ addOrEditForm.form.title }}</span>
          <el-button v-if="checkPermission(['api:admin:document:updatecontent'])" type="primary" :loading="document.loadingSave" @click="openDialog">保存文档</el-button>
        </el-header>
        <el-main class="main" style="padding:0px 5px 5px 5px;">
          <div style="height:calc(100% - 2px);">
            <my-markdown-editor ref="markdownEditor" v-model="document.form.content" :height="'100%'" />
          </div>
        </el-main>
      </el-container>    
    </el-container>

    <!-- 弹框 -->
    <el-dialog
      v-if="checkPermission(['api:material:article:add'])"
      :title="(addOrEditForm.form.id > 0 ? '编辑':'新增')"
      :visible.sync="addOrEditForm.visible"
      :close-on-click-modal="false"
      @close="closeAddOrEditForm"
    >
      <el-form ref="addOrEditForm" :model="addOrEditForm.form" label-width="100px">
        <el-tabs tab-position="left">
          <el-tab-pane label="基本信息">
            <el-form-item prop="parentIds" label="分类父级">
              <el-cascader
                :key="addOrEditForm.key"
                v-model="Category.parentIds"
                :options="articleCategories"
                :props="{ checkStrictly: true, label: 'name', value: 'id' }"
                filterable
                clearable
                style="width:100%;"
              />
            </el-form-item>
            <el-form-item label="类别名称" prop="categoryName">
              <el-input disabled v-model="addOrEditForm.categoryName" auto-complete="off" />
            </el-form-item>
            <el-form-item label="标题" prop="title">
              <el-input v-model="addOrEditForm.form.title" auto-complete="off" />
            </el-form-item>
            <el-form-item label="副标题" prop="subTitle">
              <el-input v-model="addOrEditForm.form.subTitle" auto-complete="off" />
            </el-form-item>
            <el-form-item label="作者" prop="author">
              <el-input v-model="addOrEditForm.form.author" auto-complete="off" />
            </el-form-item>
            <el-form-item label="跳转链接" prop="linkUrl">
              <el-input v-model="addOrEditForm.form.linkUrl" auto-complete="off" />
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="addOrEditForm.form.sort" controls-position="right" @change="handleChange" :min="1" :max="9999999" auto-complete="off"></el-input-number>
            </el-form-item>
            <el-form-item label="评论类型" prop="linkUrl">
              <el-select v-model="addOrEditForm.form.commentType" placeholder="请选择" auto-complete="off">
                <el-option
                  v-for="item in addOrEditForm.commentTypes"  
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="摘要" prop="digest">
              <el-input v-model="addOrEditForm.form.digest" type="textarea" rows="4"  auto-complete="off" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="标签管理">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="handleClose(tag)">
              {{tag}}
            </el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            >
            </el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">+ New Tag</el-button>
          </el-tab-pane>
          <el-tab-pane label="SEO管理">
            <el-form-item label="标题" prop="seoTitle">
              <el-input v-model="addOrEditForm.form.seoTitle" auto-complete="off" />
            </el-form-item>
            <el-form-item label="关键字" prop="seoKeywords">
              <el-input v-model="addOrEditForm.form.seoKeywords" auto-complete="off" />
            </el-form-item>
            <el-form-item label="摘要" prop="seoDescription">
              <el-input v-model="addOrEditForm.form.seoDescription" type="textarea" rows="4"  auto-complete="off" />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="基本设置">
            <el-form-item label="设置">
              <el-checkbox-group v-model="addOrEditForm.setArray">
                <el-checkbox-button label="是否置顶" name="setArray"></el-checkbox-button>
                <el-checkbox-button label="是否推荐" name="setArray"></el-checkbox-button>
                <el-checkbox-button label="是否热门" name="setArray"></el-checkbox-button>
                <el-checkbox-button label="是幻灯片" name="setArray"></el-checkbox-button>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="图片上传">
            <el-upload
              ref="upload"
              action="/api/admin/document/uploadimage"
              multiple
              :headers="token"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :before-upload="onBeforeUpload"
              :on-success="onUploadSuccess"
              :on-error="onUploadError"
              :file-list="fileList">
             <i class="el-icon-plus"></i>
            </el-upload>
            <el-dialog :visible.sync="dialogVisible">
              <img width="100%" :src="dialogImageUrl" alt="">
            </el-dialog>
          </el-tab-pane>
        </el-tabs>       
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click.native="addOrEditForm.visible = false">取消</el-button>
          <my-confirm-button type="submit" @click="save"/>
        </div>
      </template>
    </el-dialog>
  </section>
</template>

<script>
import { formatTime, treeToList, listToTree, getTreeParents } from '@/utils'
import { getArticleCategory, getArticleCategoryList } from '@/api/material/articleCategory'
import { getArticle, addArticle, editArticle } from '@/api/material/article'
import MyMarkdownEditor from '@/components/my-markdown-editor'
import MyConfirmButton from '@/components/my-confirm-button'

export default {
  path: '/AddOrEditArticle',
  name: 'AddOrEditArticle',
  components: { MyMarkdownEditor, MyConfirmButton },
  data() {
    const tabs = { doc: 'docTab', img: 'imgTab' }
    return {
      // 查询
      filter: {
        name: ''
      },
      pageLoading: false,

      showViewer: false,
      imageSrc: '',
      document: {
        tabs,
        tabName: tabs.doc,
        timer: '',
        form: {
          label: '',
          content: ''
        },
        images: [],
        loadingSave: false,
        loadingImageList: false,
        imgScrollTop: 0,
        docScrollTop: 0
      },
      addOrEditForm: {
        id: 0,
        name: '',
        parentIds: [],
        categoryName: '',
        visible: false,
        loading: false,       
        commentTypes: [{ value: 1,label: '禁止留言'},{value: 2,label: '所有人均可留言'},{value: 3,label: '仅关注后可留言'}],
        key: 1,
        setArray: [],
        form: {
          id: '',
          title: '',
          subTitle: '',
          articleCategoryId: 0,
          linkUrl: '',
          imageUrl: '',
          thumbUrl: '',
          author: '',
          content: '',
          digest: '',
          sort: 0,
          commentType: null,
          tags: '',
          seoTitle: '',
          seoKeywords: '',
          seoDescription: '',
          isTop: false,
          isRed: false,
          isHot: false,
          isSlide: false
        }
      },
      articleCategoryTree: [],
      articleCategories: [],
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',

      Category: {
        id: '',
        parentIds: [],
        name: ''
      },
      dialogImageUrl: '',
      dialogVisible: false,
      fileList:[],
      deleteImageUrl:[],
    }
  },
  computed: {
    token() {
      return { 'Authorization': 'Bearer ' + this.$store.getters.token }
    },
    isDocTab() {
      return this.document.tabName === this.document.tabs.doc
    },
    isImgTab() {
      return this.document.tabName === this.document.tabs.img
    },
    hasDocument() {
      return this.document.form.id > 0
    },
    imageIndex() {
      let previewIndex = 0
      const srcIndex = this.document.images.findIndex(a => a.src === this.imageSrc)
      if (srcIndex >= 0) {
        previewIndex = srcIndex
      }
      return previewIndex
    },
    imageUrls() {
      return this.document.images.map(a => a.src)
    }  
  },
  watch: {
    'document.form.content'(newVal, oldVal) {
      if (!(this.document.form.id > 0) || this.document.form._first) {
        this.document.form._first = false
        this.clearTimer()
        return
      }

      this.clearTimer()

      const me = this
      this.document.timer = setTimeout(function() { me.save(true) }, 10000)
    },
    'document.tabName'(newVal, oldVal) {
      const $el = this.$refs.tabContainer?.$el
      if ($el) {
        const scrollTop = $el.scrollTop
        let toScrollTop = 0
        if (newVal === this.document.tabs.doc) {
          toScrollTop = this.document.docScrollTop
          this.document.imgScrollTop = scrollTop > 0 ? scrollTop : 0
        } else if (newVal === this.document.tabs.img) {
          toScrollTop = this.document.imgScrollTop
          this.document.docScrollTop = scrollTop > 0 ? scrollTop : 0
        }
        this.$nextTick(function() {
          $el.scrollTop = toScrollTop
        })
      }
    }
  },
  mounted() {
    this.onGetCategoryList(),
    this.getArticle()
  },
  beforeDestroy() {
    this.clearTimer()
  },
  methods: {
    // 清除自动保存任务
    clearTimer() {
      if (this.document.timer) {
        clearTimeout(this.document.timer)
        this.document.timer = ''
      }
    },
    // 保存文档
    async save() {
      let autoSave = false

      this.addOrEditForm.loading = true
      const para = _.cloneDeep(this.addOrEditForm)

      para.form.articleCategoryId = this.Category.parentIds.pop()
      para.form.tags = this.dynamicTags.join(',')

      para.form.isTop = this.addOrEditForm.setArray.find(value=> value==='是否置顶') === '是否置顶'? true : false
      para.form.isRed = this.addOrEditForm.setArray.find(value=>value==='是否推荐') === '是否推荐'? true : false
      para.form.isHot = this.addOrEditForm.setArray.find(value=>value==='是否热门') === '是否热门'? true : false
      para.form.isSlide = this.addOrEditForm.setArray.find(value=>value==='是幻灯片') === '是幻灯片'? true : false

      if (this.document.timer) {
        clearTimeout(this.document.timer)
        this.document.timer = ''
      }
  
      this.document.form.html = this.$refs.markdownEditor.getHtml()
      para.form.content = this.document.form.html

      this.document.loadingSave = true
      let res = null
      if(JSON.stringify(this.$route.params)=='{}') {
        var imgs = []
        this.document.images.forEach(d => {
           imgs.push(d.src)
        })
        para.form.imageUrl = imgs.join(',')
        res = await addArticle(para.form)
      }
      else {
        para.form.id = this.$route.params.id

        this.document.images.forEach(d => {
           this.fileList.push({
            name: d.uid,
            url: d.src
          })
        })

        var imgs = []
        this.fileList.forEach(f => {
          imgs.unshift(f.url)
        })
        para.form.imageUrl = imgs.join(',')
        var imgs = []
        this.fileList = []
        this.document.images = []

        res = await editArticle(para.form)
      }

      this.document.loadingSave = false
      if (!res?.success) {
        return
      }

      this.addOrEditForm.visible = false
      this.document.form.version++
      if (!autoSave) {
        this.$message({
          message: this.$t('material.saveOk'),
          type: 'success'
        })
      }
      this.getArticle()
    },
     // 获取列表
    async onGetCategoryList() {
      const para = {
        key: this.filter.name
      }
      this.listLoading = true
      const res = await getArticleCategoryList(para)
      this.listLoading = false

      if (!res?.success) {
        return
      }

      const list = _.cloneDeep(res.data)

      const keys = list.filter(l => l.parentId === 0).map(l => l.id + '')
      this.expandRowKeys = keys

      this.articleCategories = listToTree(_.cloneDeep(list), {
        id: 0,
        parentId: 0,
        name: '根节点'
      })

      list.forEach(d => {
        d._loading = false
      })
      const tree = listToTree(list)
      this.articleCategoryTree = tree
    },
    openDialog() {
      this.addOrEditForm.visible = true
    },
    closeAddOrEditForm() {
      //this.$refs.addOrEditForm.resetFields()
      ++this.addOrEditForm.key
    },
    addOrEditFormValidate: function() {
      let isValid = false
      this.$refs.addOrEditForm.validate(valid => {
        isValid = valid
      })
      return isValid
    },
    async handleChange(value) {
      this.addOrEditForm.form.sort = value
    },
    handleClose(tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
    },

    showInput() {
      this.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.dynamicTags.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    async getArticle() {     
      if(JSON.stringify(this.$route.params)=='{}') {
        return
      }

      const para = {
        id: this.$route.params.id
      }
      const res = await getArticle(para)
      if (!res?.success) {
        return
      }
      this.addOrEditForm.form = res.data

      this.document.form.content = this.addOrEditForm.form.content

      if(this.addOrEditForm.form.tags.length > 0) {
        this.dynamicTags = this.addOrEditForm.form.tags.split(',')
      }

      if(this.addOrEditForm.form.imageUrl.length > 0) {       
        var imgs = [] 
        var imgs = this.addOrEditForm.form.imageUrl.split(',')

        var i = 0
        this.fileList = []
        imgs.forEach(m => {
          this.fileList.unshift({
            name: i,
            url: m
          })
        })
      }
      if(this.addOrEditForm.form.isTop) {
        this.addOrEditForm.setArray.push('是否置顶')
      }
      if(this.addOrEditForm.form.isRed) {
        this.addOrEditForm.setArray.push('是否推荐')
      }
      if(this.addOrEditForm.form.isHot) {
        this.addOrEditForm.setArray.push('是否热门')
      }
      if(this.addOrEditForm.form.isSlide) {
        this.addOrEditForm.setArray.push('是幻灯片')
      }
      this.getCategory(this.addOrEditForm.form.articleCategoryId)
    },
    async getCategory(id) {
      const res = await getArticleCategory({ id: id })
      if (res && res.success) {
        const parents = getTreeParents(this.articleCategoryTree, id)
        const parentIds = parents.map(p => p.id)
        parentIds.unshift(0)

        const data = res.data
        data.parentIds = parentIds
        this.Category = data
        this.addOrEditForm.categoryName = this.Category.name
      }     
    },
    handleRemove(file, fileList) {
      if (this.fileList.length > 0 ) {
        var index = this.fileList.findIndex(item =>{
　　　　　　　　　    if (item.url === file.url) {
　　　　　　　　　　　  return true
　　　　　　　　　　  }
　　　　　         })
　　　   this.fileList.splice(index,1)
      }     
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 上传前
    onBeforeUpload(file) {
      this.document.images.unshift({
        loading: true,
        src: '',
        uid: file.uid
      })
    },
    // 上传成功
    onUploadSuccess(res, file, fileList) {
      const img = this.document.images.find(a => a.uid === file.uid)
      img.loading = false
      if (!res?.code === 1) {
        return
      }
      img.src = res.data
    },
    // 上传失败
    onUploadError(err, file) {
      const res = err.message ? JSON.parse(err.message) : {}
      if (!(res?.code === 1)) {
        if (res.msg) {
          this.$message({
            message: res.msg,
            type: 'error'
          })
        }
      }
      const img = this.document.images.find(a => a.uid === file.uid)
      img.loading = false
    }
  }
}
</script>

<style lang="scss" scoped>
.image-container{
  height:120px;
  line-height: 120px;
  width:100%;
  cursor: pointer;
  margin-top:5px;
  // border: 1px solid #d7dae2;
  background: #f5f7fa;
  &:hover{
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  }
}

::v-deep .image-slot{
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.mc-upload-list{
  .mc-upload-list__item{
    position: relative;
    .mc-upload-list__item-actions{
      position: absolute;
      bottom: 0;
      left: 5px;
      right: 5px;
      color: #fff;
      background-color: rgba(0,0,0,.5);
      text-align: right;
      font-size: 18px;
      padding: 3px 10px;
      opacity: 0;
      transition: opacity .3s;
      span{
        cursor: pointer;
        display: inline-block;
        &+span{
          margin-left:15px;
        }
        &:hover{
          color: #409eff;
        }
      }
    }
    &:hover{
      .mc-upload-list__item-actions{
        opacity: 1;
      }
    }
  }
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
